package com.cuixichang.minimalism.domain;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cuixichang.minimalism.acl.RelevanceDesign;
import com.cuixichang.minimalism.basal.core.RelationDict;
import com.cuixichang.minimalism.core.mybatis.cnstants.BaseFieldNames;
import com.cuixichang.minimalism.core.security.userdetails.CredentialDetail;
import com.cuixichang.minimalism.service.ISystemService;
import com.cuixichang.minimalism.transfer.dto.*;
import com.cuixichang.minimalism.transfer.po.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ISystemCommandServiceImpl implements ISystemCommandService{
    @Autowired
    private ISystemService iSystemService;
    @Autowired
    private RelevanceDesign relevanceDesign;

    @Override
    public Page<ISystemDTO> selectPageByConditional(ISystemDTO iSystemDTO, Long pageNo, Long pageSize) {
        return iSystemService.selectPage(iSystemDTO,pageSize,pageNo,(iSystem, queryWrapper) -> {
            Long createLoginId = iSystem.getCreateLoginId();
            if(Objects.nonNull(createLoginId)){
                List<Long> beAuthLoginIds = relevanceDesign.beAuthLoginIds(createLoginId);
                queryWrapper.in(!CollectionUtils.isEmpty(beAuthLoginIds), BaseFieldNames.CREATE_LOGIN_ID, beAuthLoginIds);
            }
            String keyword = iSystemDTO.getKeyword();
            queryWrapper.like(StrUtil.isNotBlank(keyword),"system_name",keyword);
            iSystem.setCreateLoginId(null);
        });
    }

    @Override
    public List<RelationDict> selectQuerySystemParams(String systemCode, CredentialDetail credentialDetail) {
        Assert.hasText(systemCode,"系统编码不能为空,请检查");
        return iSystemService.selectList(ISystemDTO.builder().isEnable(true).build(),(iSystem, queryWrapper)->{
            queryWrapper.and((wrapper)->{
                wrapper.eq("system_code",systemCode);
                if(Objects.nonNull(credentialDetail)){
                    List<Long> beAuthLoginIds = relevanceDesign.beAuthLoginIds(credentialDetail.getLoginId());
                    wrapper.or().in(!CollectionUtils.isEmpty(beAuthLoginIds), BaseFieldNames.CREATE_LOGIN_ID, beAuthLoginIds);
                }
            });
        }).stream().map(system-> RelationDict.builder().key(system.getSystemName()).value(system.getSystemCode()).build())
                .collect(Collectors.toList());
    }
}
